<?php
/**
 *接受产品数据管理系统关于产品的数据
 *@author shipanpan
 */
class Interface_PdmController extends Controller_Interface {

	public function init() {
		parent::init();
		$this->writeDb = Model_Db::getInstance('write_db');
	}

	/**
	 * 同步产品数据
	 * @return [type] [description]
	 */
	public function synProductAction() {
		$requestParams = $this->getRequest()->getParams();

		if (!$this->verifySign($requestParams['json'], $requestParams['key'])) {
			$this->log->record('PDM推送产品基础信息处理出错：原因签名错误！', Log::WARN);
			return $this->error(-1, '签名验证不通过');
		}

		$productInformData = json_decode($requestParams['json'], true);
		$synResult = [];
		foreach ($productInformData as $oneGoods) {
			if (empty($oneGoods) || !is_array($oneGoods) || !isset($oneGoods['goods_sn'])) {
				continue;
			}
			$this->writeDb->beginTransaction();
			try {
				$this->_saveProduct($oneGoods);
				$this->_saveProductPurchase($oneGoods);
				$this->_saveProductPurchaseInfo($oneGoods);
				$this->_saveSupplier($oneGoods);

				$synResult[] = ['goods_sn' => $oneGoods['goods_sn'], 'status' => 1];
				$this->writeDb->commit();
			} catch (Exception $e) {
				$this->writeDb->rollBack();
				$synResult[] = ['goods_sn' => $oneGoods['goods_sn'], 'status' => 2];
				$this->log->record($e->getMessage(), Log::WARN);
			}
		}

		exit(json_encode($synResult));
	}

	/**
	 * 保存产品信息
	 * @param  array $productInformData 产品管理系统通知过来的某个产品信息数据
	 * @return bool 保存成功返回true，发生错误抛出异常
	 */
	private function _saveProduct(array $productInformData) {
		$needField = [
			'goods_sn',
			'catalog_id',
			'goods_type',
			'goods_name',
			'barcode',
			'sample_already',
			'need_qc',
			'is_edit_same_price',
			'charger_spec',
			'stock_attribute',
			'product_name',
			'researcher',
			'title',
			'product_status',
			'sale_price_base',
			'create_user',
			'create_time',
			'update_user',
			'update_time',
			'shelf_time',
			'draft_status',
			'recommend_level',
			'wh_code',
			'brand_code',
			'edit_status',
			'online_status',
			'manage_life',
			'product_life',
			'purchase_life',
			'is_making',
			'is_oem',
			'thumb',
			'ori',
		];
		//通知字段名与本地数据库字段名映射转换
		$localColName = ['ori' => 'original_img_url', 'thumb' => 'thumb_url'];

		$product = [];
		foreach ($needField as $field) {
			//有些字段的通知值是null，所以不用isset判断
			if (!array_key_exists($field, $productInformData)) {
				$errorMsg = "从PDM同步产品{$productInformData['goods_sn']}信息失败,原因是:接口通知字段" . print_r($productInformData, true) . '未有产品信息字段:' . $field;
				throw new Exception($errorMsg);
			}
			$localField = $localColName[$field] ?? $field;
			$product[$localField] = $productInformData[$field];
		}
		return Model_Base::insertOrUpdate($this->writeDb, 'p_product', $product);
	}

	/**
	 * 保存产品采购记录
	 * @param  array $productInformData 产品管理系统通知过来的某个产品信息数据
	 * @return bool 保存成功返回true，发生错误抛出异常
	 */
	private function _saveProductPurchase(array $productInformData) {
		$needField = [
			'goods_sn',
			'purchaser',
			'buy_url',
			'supplier_product_sn',
			'supplier_sn',
			'purchase_price',
			'goods_resource_status',
			'delivery_info',
			'delivery_user',
			'delivery_time',
			'supplier_remark',
			'purchase_price_unit',
			'purchase_price_base',
		];

		$productPurchase = [];
		foreach ($needField as $field) {
			if (!array_key_exists($field, $productInformData)) {
				$errorMsg = "从PDM同步产品{$productInformData['goods_sn']}信息失败,原因是:接口通知字段" . print_r($productInformData, true) . '未有采购记录字段:' . $field;
				throw new Exception($errorMsg);
			}
			$productPurchase[$field] = $productInformData[$field];
		}
		return Model_Base::insertOrUpdate($this->writeDb, 'p_product_purchase', $productPurchase);
	}

	/**
	 * 保存产品采购信息
	 * @param  array $productInformData 产品管理系统通知过来的某个产品信息数据
	 * @return bool 保存成功返回true，发生错误抛出异常
	 */
	private function _saveProductPurchaseInfo(array $productInformData) {
		$needField = [
			'goods_sn',
			'package_num',
			'min_order',
			'delivery_min_day',
			'delivery_max_day',
			'expect_life_cycle',
			'production_cycle_min',
			'production_cycle_max',
			'agent_inventory',
		];

		$productStock = [];
		foreach ($needField as $field) {
			if (!array_key_exists($field, $productInformData)) {
				$errorMsg = "从PDM同步产品{$productInformData['goods_sn']}信息失败,原因是:接口通知字段" . print_r($productInformData, true) . '未有采购信息字段:' . $field;
				throw new Exception($errorMsg);
			}
			$productStock[$field] = $productInformData[$field];
		}

		return Model_Base::insertOrUpdate($this->writeDb, 'p_product_purchase_info', $productStock);
	}

	/**
	 *保存供应商信息
	 * @param  array $productInformData 产品管理系统通知过来的某个产品信息数据
	 * @return bool 保存成功返回true，发生错误抛出异常
	 */
	private function _saveSupplier(array $productInformData) {
		$needField = [
			'supplier_sn',
			'supplier_name',
		];
		$supplier = [];
		foreach ($needField as $field) {
			if (!array_key_exists($field, $productInformData)) {
				$errorMsg = "从PDM同步产品{$productInformData['goods_sn']}信息失败,原因是:接口通知字段" . print_r($productInformData, true) . '未有供应商信息字段:' . $field;
				throw new Exception($errorMsg);
			}

			if (trim($productInformData[$field])) {
				$supplier[$field] = $productInformData[$field];
			}
		}

		return $this->_saveOneSupplier($supplier['supplier_sn'], $supplier['supplier_name']);
	}

	/**
	 * 保存供应商信息
	 * @param  [type] $supplierCode 供应商唯一编码
	 * @param  [type] $supplierName 供应商名称
	 * @param  [type] $purchaser    供应商采购员
	 * @return [bool
	 */
	private function _saveOneSupplier($supplierCode, $supplierName) {
		$supplierCode = $this->writeDb->quote($supplierCode);
		$supplierName = $this->writeDb->quote($supplierName);
		return $this->writeDb->query("insert into p_product_supplier (sp_code,sp_name) values($supplierCode,$supplierName)  on duplicate key update sp_name=$supplierName");
	}

	/**
	 * 同步清仓信息
	 * @return [type] [description]
	 */
	public function synProductClearanceAction() {
		$requestParams = $this->getRequest()->getParams();

		//这里竟然是直接对比密钥
		$key = self::getKey();
		if ($key != $requestParams['keys_code']) {
			$errorMsg = '同步清仓接口密钥匹配错误,' . '传过来的密钥是:' . $requestParams['keys_code'] . ';我们的密钥是:' . $key;
			$this->log->record($errorMsg, Log::WARN);
			$this->_helper->json(['status' => 'fail', 'msg' => '密钥匹配错误']);
		}

		$data = $requestParams['data'];
		$data = json_decode($data, true);
		if (!is_array($data) || !$data) {
			$errorMsg = '同步清仓接口出现错误,数据格式错误:' . print_r($requestParams, true);
			$this->log->record($errorMsg, Log::WARN);
			$this->_helper->json(['status' => 'fail', 'msg' => $errorMsg]);
		}

		$result = [];
		foreach ($data as $clearanceData) {
			$this->writeDb->beginTransaction();
			try {
				$isClearance = $clearanceData['is_clearance'] == 1 ? 1 : 2;
				$insertOrUpdateData = [
					'goods_sn' => $clearanceData['goods_sn'],
					'warehouse' => $clearanceData['wh_code'],
					'is_clearance' => $isClearance,
					'is_clearance_update_time' => time(),
				];
				Model_Base::insertOrUpdate($this->writeDb, 'p_warehouse_product', $insertOrUpdateData);
				$result[] = ['syn_status' => 1, 'id' => $clearanceData['id']];
				$this->writeDb->commit();
			} catch (Exception $e) {
				$this->writeDb->rollBack();
				$errorMsg = "导入商品:" . $clearanceData['goods_sn'] . '，在仓库：' . $clearanceData['wh_code'] . '的清仓数据错误，错误原因:' . $e->getMessage();
				$result[] = ['syn_status' => 0, 'id' => $clearanceData['id'], 'response_content' => $errorMsg];
				$this->log->record($errorMsg, Log::WARN);
			}
		}
		$this->log->record('同步清仓数据成功！');
		$this->_helper->json([$result]);
	}
}